package generater;

import cn.itlaobing.eshop.dao.BaseDao;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.junit.Test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URL;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/11/7 0007.
 */
public class EntityGenerater extends BaseDao{

    private Logger log=Logger.getLogger(EntityGenerater.class);

    @Test
    public void generateEntity() throws SQLException, IOException {
        String tableName="itlb_focuss";
        //获取建表的sql语句
       String ddl= getCreateTableDdl(tableName);
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
       log.info(ddl);
        List<TableField> fieldList= getTableFieldList(ddl);
        //实体类名
        String entityClassName=tableNameToClassName(tableName);
        log.info(entityClassName);

        ///////////使用velocity 模板生成类文件
        VelocityEngine ve = new VelocityEngine();
        Properties p = new Properties();
        //加载classpath目录下的vm文件
        p.setProperty("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //定义字符集
        p.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
        p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        ve.init(p);
        //取得velocity的模版
        Template t = ve.getTemplate("template/tpl_entity.vm");
        //取得velocity的上下文context
        VelocityContext context = new VelocityContext();
        context.put("entityClassName",entityClassName);
        context.put("fieldList",fieldList);

//        StringWriter writer = new StringWriter();
//        //转换输出
//        t.merge(context, writer);
//        System.out.println(writer.toString());

        String projectRootPath=getProjectRootDir();
        File entityPackageDir=new File(projectRootPath,"/src/main/java/cn/itlaobing/eshop/entity");

        File entityClassFile=new File(entityPackageDir,entityClassName+".java");

        FileWriter fileWriter=new FileWriter(entityClassFile);
        t.merge(context, fileWriter);
        fileWriter.close();


    }

    /**
     * 获取项目目录
     * @return
     */
    private String getProjectRootDir(){
        URL url=this.getClass().getResource("/");
        return url.toString().replace("file:/","").replace("target/test-classes/","");
    }


    private String tableNameToClassName(String tableName){
        StringBuilder sb=new StringBuilder(tableName);
        //首字母变大写
        Character firstLetter=sb.charAt(0);
        sb.replace(0,1,firstLetter.toString().toUpperCase());
        while(sb.indexOf("_")!=-1){
            int index=sb.indexOf("_");
            Character followLetter=sb.charAt(index+1);
            sb.replace(index,index+2,followLetter.toString().toUpperCase());
        }
        return sb.toString();
    }

    private List<TableField> getTableFieldList(String ddl){
        List<TableField> result=new ArrayList<>();
        String rex="`(\\w+)` (.+?) .+COMMENT '(.+?)'";
        Pattern rexPattern=Pattern.compile(rex);
        Matcher matcher=rexPattern.matcher(ddl);
        while(matcher.find()){
            log.info(matcher.group(1));
            log.info(matcher.group(2));
            log.info(matcher.group(3));

            TableField tableField=new TableField();
            tableField.setFieldName(matcher.group(1));
            tableField.setDateType(matcher.group(2));
            tableField.setComment(matcher.group(3));
            result.add(tableField);
        }
        return  result;

    }


    private String getCreateTableDdl(String tableName) throws SQLException {
        QueryRunner runner=new QueryRunner(this.getDataSource());
        String sql="SHOW CREATE TABLE "+tableName;
        MapHandler mapHandler=new MapHandler();
        Map<String,Object> map=runner.query(sql,mapHandler);
       if(map==null ||map.size()==0){
            throw new RuntimeException("数据库中表"+tableName+"不存在");
       }
        return map.get("Create Table").toString();
    }


}
